<?php
namespace app\api\model\wine;

use app\common\model\BaseModel;

class Degain extends BaseModel{
    protected $autoWriteTimestamp = true;

    /**
     * 添加金币记录
     * @param int $user_id 推荐者
     * @param int $sid 被推荐者
     * @param float $earnings 积分收益
     * @param int $gain_type 收益类型1推荐奖励,2分享奖励,3活动报名推荐奖励,4活动报名出组奖励,5活动报名交通补贴
     * @return bool
     */
    public static function AddRecommend(int $user_id,int $sid,float $earnings,int $gain_type=1):bool
    {
        return self::transaction(function () use ($user_id,$gain_type,$earnings,$sid){
            // 添加金币记录
            self::create([
                'store_id' => getStoreId(),
                'user_id' => $user_id,
                'gain_type' => $gain_type,
                'earnings' => $earnings,
                'sid' => $sid
            ]);
            // 金币汇总 必须参加完项目活动才给金币，所以这里只有给金币记录
            /*$r = Dermember::setGold($user_id,$earnings,'inc');
            return $r !== false;*/
            return true;
        });
    }

    /**
     * 关联用户表
     * @return \think\model\relation\HasOne
     */
    public function user(){
        return $this->hasOne(\app\common\model\User::class,'user_id','user_id')
            ->with('avatar')
            ->bind(['nick_name','gender','avatar_url']);
    }

    /**
     * 获取用户金币记录
     * @param int $user_id
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public static function getGoldList(int $user_id){
        return self::where(['user_id'=>$user_id,'status'=>1])
            ->with('user')
            ->paginate(15);
    }
}
